import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '@/http/api';

export const useOrganizationStore = defineStore('organization', () => {
  const organizations = ref([]);
  const loading = ref(false);

  const setOrganization = (tree) => {
    organizations.value = [tree];
  };

  const getOrganization = async() => {
    if (organizations.value && organizations.value.length > 0) {
      return organizations.value;
    } else {
      return await loadOrganization();
    }
  };

  const loadOrganization = async() => {
    if (organizations.value && organizations.value.length > 0) {
      loading.value = false;
      return organizations.value;
    }

    if (loading.value) {
      await sleep(100);
      return await loadOrganization();
    }

    loading.value = true;
    if (organizations.value && organizations.value.length) {
      loading.value = false;
      return organizations.value;
    } else {
      const res = await api.post('/organization/queryTree').catch(() => {
        loading.value = false;
      });
      loading.value = false;
      if (res.code === "1") {
        setOrganization(res.data);
        return organizations.value;
      }
    }
  };

  const reloadOrganization = async() => {
    organizations.value = [];
    await getOrganization();
  };

  const sleep = async (d) => {
    return new Promise((resolve) => setTimeout(resolve, d));
  };

  return {
    getOrganization,
    reloadOrganization
  };
});
